package com.zero.common.security.service;

import com.zero.common.core.constant.CacheConstants;
import com.zero.common.core.constant.Constants;
import com.zero.common.core.constant.UserConstants;
import com.zero.common.system.domain.entity.SysUser;
import com.zero.common.security.vo.LoginUser;
import com.zero.common.core.exception.user.*;
import com.zero.common.core.redis.RedisTemplateHelper;
import com.zero.common.core.exception.ServiceException;
import com.zero.common.core.utils.DateUtils;
import com.zero.common.core.utils.MessageUtils;
import com.zero.common.core.utils.StringUtils;
import com.zero.common.core.utils.ip.IpUtils;
import com.zero.common.system.service.ISysConfigService;
import com.zero.common.threadpool.AsyncManager;
import com.zero.common.threadpool.AsyncFactory;
import com.zero.common.security.context.LoginAuthenticationContextHolder;
import com.zero.common.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisTemplateHelper redisTemplateHelper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private AsyncManager asyncManager;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        // 验证码校验 没抛异常则验证通过
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            // new 一个上下文对象(账号+密码)
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            // 给ThreadLocal设置当前账号密码
            LoginAuthenticationContextHolder.setContext(authenticationToken);
            /*
                AuthenticationManager接口的 的 authenticate() 方法 -> Authentication authenticate(Authentication authentication) throws AuthenticationException;
                会去调用 UserDetailsServiceImpl.loadUserByUsername()
                原因：
                1. AuthenticationManager 在 SecurityConfig 配置中 被 指定了
                    校验的接口(org.springframework.security.core.userdetails.UserDetailsService)
                2. 而 UserDetailsServiceImpl 实现了该接口
                    并重写了 loadUserByUsername方法 -> UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
            */
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) { // BadCredentialsException extends AuthenticationException
                // 账号或密码错误
//                asyncManager.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
//                asyncManager.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            LoginAuthenticationContextHolder.clearContext(); // 清除上下文
        }
        // 记录登陆成功日志
//        asyncManager.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        // 当前用户详细信息
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 更新数据库登录信息(IP和登陆时间)
        updateLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     验证码唯一标识
     */
    public void validateCaptcha(String username, String code, String uuid) {
        // 判断登录是否需要验证码
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        // 需要验证码
        if (captchaEnabled) {
            // redis-验证码-key
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            // 查验证码缓存
            String captcha = redisTemplateHelper.getCacheObject(verifyKey);
            // 验证码为空 抛出验证码超时异常
            if (captcha == null) {
//                asyncManager.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            // 验证码不为空 删除验证码 若输入验证码错误 抛出验证码错误异常
            redisTemplateHelper.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha)) {
//                asyncManager.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
//            asyncManager.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
//            asyncManager.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
//            asyncManager.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
//            asyncManager.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 更新数据库登录信息(IP和登陆时间)
     * @param userId 用户ID
     */
    public void updateLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
